package edu.fpa.day0717;

import java.util.ArrayList;

public class Test04<E> {
    private Object[] elementData;
    private int size;

    private static final int DEFALT_CAPACITY = 10;

    public Test04() {
        elementData = new Object[DEFALT_CAPACITY];
    }

    public Test04(int capacity) {
        elementData = new Object[capacity];
    }

    public void add(E element) {
        //什么时候扩容
        if(size == elementData.length) {
            //扩容操作
            Object[] newArray = new Object[elementData.length+(elementData.length<<1)];//10-->10+10/2
            System.arraycopy(elementData, 0, newArray, 0, elementData.length);
            elementData = newArray;
        }
        elementData[size++] = element;
    }

    public E get(int index) {
        return (E)elementData[index];
    }

    public void set(E element,int index) {
        //索引合法判断【0,size】 eg.10  0-9
        if(index<0||index>size-1) {
            //不合法
            throw new RuntimeException("索引不合法："+index);
        }
        elementData[index] = element;
    }

    public void remove(E element) {                          //本节内容
        //element将它和所有元素挨个比较，获得第一个为true的，返回
        for(int i=0;i<size;i++) {
            if(element.equals(get(i))) { //容器中所有操作的比较操作都用equals而不是==
                //讲该元素从此处移除
                remove(i);
            };
        }
    }
    public void remove(int index) {                         //本节内容
        //a,b,c,d,e,f,g,h
        //a,b,c,e,f,g,h
        int numMoved = elementData.length-index-1;
        if(numMoved>0) {
            System.arraycopy(elementData, index+1, elementData, index, numMoved);
        }
        elementData[--size] = null;
    }

    public int size() {
        return size;
    }
    public boolean isEmpty() {
        return size==0?true:false;
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        //[a,b,c]
        sb.append("[");
        for(int i=0;i<size;i++) {
            sb.append(elementData[i]+",");
        }
        sb.setCharAt(sb.length()-1,']');
        return super.toString();
    }
    public static void main(String[] args) {
        ArrayList s1 = new ArrayList();
        for(int i=0;i<15;i++) {
            s1.add("liu"+i);
        }

        s1.set(10, "qqq");
        System.out.println(s1);
        System.out.println(s1.get(10));
        s1.remove(5);
        System.out.println(s1);
        System.out.println(s1.isEmpty());
    }
}
